﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Cesave.Domain.PermisosModule.Resources;
using Cesave.Domain.Core;
using System.Data;

namespace Cesave.Domain.PermisosModule.Contracts.RiegoFuentes
{
	/// <summary>
	/// 
	/// </summary>
	public class RiegoFuenteService
		: IRiegoFuenteService
	{
		#region Private properties

		/// <summary>
		/// 
		/// </summary>
		private IRiegoFuenteRepository _riegoFuenteRepository;

		#endregion

		#region Constructor

		/// <summary>
		/// 
		/// </summary>
		/// <param name="riegoFuenteRepository"></param>
		public RiegoFuenteService(IRiegoFuenteRepository riegoFuenteRepository)
		{
			if (riegoFuenteRepository == null)
				throw new ArgumentNullException(Messages.exception_DependenciesAreNotInitialized, "riegoFuenteRepository");
			_riegoFuenteRepository = riegoFuenteRepository;
		}

		#endregion

		#region IRiegoFuenteService Members

		/// <summary>
		/// 
		/// </summary>
		/// <param name="riegoFuente"></param>
		public void AddRiegoFuente(Entities.RiegoFuente riegoFuente)
		{
			if (riegoFuente == null)
				throw new ArgumentNullException(Messages.exception_InvalidArgument, "riegoFuente");
			IUnitOfWork unitOfWork = _riegoFuenteRepository.StoreContext;
			_riegoFuenteRepository.Add(riegoFuente);
			try
			{
				unitOfWork.Commit();
			}
			catch (OptimisticConcurrencyException)
			{
				unitOfWork.RollbackChanges();
				unitOfWork.CommitAndRefreshChanges();
			}
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="riegoFuente"></param>
		public void ChangeRiegoFuente(Entities.RiegoFuente riegoFuente)
		{
			if (riegoFuente == null)
				throw new ArgumentNullException(Messages.exception_InvalidArgument, "riegoFuente");
			IUnitOfWork unitOfWork = _riegoFuenteRepository.StoreContext;
			_riegoFuenteRepository.Modify(riegoFuente);
			try
			{
				unitOfWork.Commit();
			}
			catch (OptimisticConcurrencyException)
			{
				unitOfWork.RollbackChanges();
				unitOfWork.CommitAndRefreshChanges();
			}
		}

		/// <summary>
		/// 
		/// </summary>
		/// <returns></returns>
		public List<Entities.RiegoFuente> FindAllRiegoFuentes()
		{
			return _riegoFuenteRepository.GetAll().OrderBy(f => f.Nombre).ToList();
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="status"></param>
		/// <returns></returns>
		public List<Entities.RiegoFuente> FindRiegoFuentesByStatus(bool status = true)
		{
			RiegoFuentesByStatusSpecification specification = new RiegoFuentesByStatusSpecification(status);
			return _riegoFuenteRepository.FindRiegoFuentesByStatus(specification).ToList();
		}

		#endregion

		#region IDisposable Members

		public void Dispose()
		{
			if (_riegoFuenteRepository != null && _riegoFuenteRepository.StoreContext != null)
				_riegoFuenteRepository.StoreContext.Dispose();
		}

		#endregion
	}
}